﻿using System;

namespace Assets.Scripts.Util.StringUtil
{
    public unsafe class StringUtil
    {
        public static void ToLower(string str)
        {
            fixed (char* c = str)
            {
                var length = str.Length;
                for (var i = 0; i < length; i++)
                {
                    c[i] = char.ToLower(c[i]);
                }
            }
        }

        public static int Split(string str, char split, string[] toFill)
        {
            if (str.Length == 0)
            {
                toFill[0] = string.Empty;
                return 0;
            }

            var length = str.Length;
            var ret = 0;
            fixed (char* p = str)
            {
                var start = 0;
                for (var i = 0; i < length; i++)
                {
                    if (p[i] == split)
                    {
                        toFill[ret++] = new string(p, start, i - start);
                        start = i + 1;
                        if (i == length - 1)
                        {
                            toFill[ret++] = string.Empty;
                        }
                    }
                }

                if (start < length)
                {
                    toFill[ret++] = new string(p, start, length - start);
                }
            }

            return ret;
        }

        public static void SetLength(string str, int length)
        {
            fixed (char* s = str)
            {
                int* ptr = (int*) s;
                ptr[-1] = length;
                s[length] = '\0';
            }
        }

        public static string SubString(string str, int start, int length = 0)
        {
            if (length <= 0)
            {
                length = str.Length - start;
            }

            if (length > str.Length - start)
            {
                throw new IndexOutOfRangeException();
            }

            fixed (char* c = str)
            {
                // unsafe
                return new string(c, start, length);
            }
        }
    }
}